package com.pshcp.tool;

import com.alibaba.fastjson.JSON;
import com.external.hospital.ap.domain.SavePatientDTO;
import com.external.hospital.ap.domain.SavePatientInquirerDTO;
import com.external.hospital.chatmessage.domain.SendPatientsMedicalRecordDTO;
import com.external.hospital.chatmessage.domain.SendSysMessageDTO;
import com.external.hospital.chatmessage.domain.UploadMediaDTO;
import com.framework.common.config.CustomConf;
import com.framework.tool.CommonTool;
import com.framework.util.DateUtil;
import com.framework.util.SystemUtil;
import com.google.common.collect.Lists;
import com.icbc.api.internal.util.StringUtils;
import com.pshcp.ao.chatmessage.SendShareArticleMessageAO;
import com.pshcp.ao.chatmessage.SendSysMessageAndPatientsMedicalRecordAO;
import com.pshcp.ao.chatmessage.UploadMediaAO;
import com.pshcp.common.tool.PhotoTools;
import com.pshcp.domain.model.*;
import com.pshcp.manager.messagenotification.MessageNotificationContentDTO;
import com.pshcp.manager.messagenotification.MessageNotificationDTO;
import com.pshcp.patient.tool.PatientTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2022/12/11 16:45
 */
public class ChatMessageTool {
    public static UploadMediaDTO buildUploadMediaDTO(UploadMediaAO uploadMediaAO, MultipartFile multipartFile) {
        UploadMediaDTO uploadMediaDTO = CommonTool.copyProperties(uploadMediaAO, UploadMediaDTO.class);
        uploadMediaDTO.setFilename(multipartFile.getOriginalFilename());
        File file = transferToFile(multipartFile);
        uploadMediaDTO.setFile(file);
        return uploadMediaDTO;
    }


    private static File transferToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            file = File.createTempFile(originalFilename, prefix);
            multipartFile.transferTo(file);
            //删除
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static SendSysMessageDTO buildSendSysMessage(OnlineSession onlineSession) {
        SendSysMessageDTO sendSysMessageDTO = new SendSysMessageDTO();
        sendSysMessageDTO.setContent("[系统提醒]医生会尽快为您解答，如未得到及时回复，可能医生正在忙碌，请您耐心等待");
        sendSysMessageDTO.setDoctorId(onlineSession.getDoctorId());
        sendSysMessageDTO.setPatientId(onlineSession.getPatientId());
        return sendSysMessageDTO;
    }

    public static SendPatientsMedicalRecordDTO buildSendPatientsMedicalRecord(OnlineSession onlineSession, Patient patient, PatientOnlineMedicalRecords medicalRecords,
                                                                              SendSysMessageAndPatientsMedicalRecordAO sendSysMessageAndPatientsMedicalRecordAO,
                                                                              Doctor doctor, CustomConf customConf) {
        SendPatientsMedicalRecordDTO sendPatientsMedicalRecordDTO = new SendPatientsMedicalRecordDTO();
        sendPatientsMedicalRecordDTO.setAge(PatientTools.getAge(patient.getIdCardNo()));
        sendPatientsMedicalRecordDTO.setAgeStr(sendPatientsMedicalRecordDTO.getAge() + "");
        sendPatientsMedicalRecordDTO.setAgeUnit("岁");
        sendPatientsMedicalRecordDTO.setGender(PatientTools.getSexDesc(patient.getIdCardNo()).equals("女") ? 0 : 1);
        sendPatientsMedicalRecordDTO.setIdCard(patient.getIdCardNo());
        sendPatientsMedicalRecordDTO.setDoctorId(onlineSession.getDoctorId());
        sendPatientsMedicalRecordDTO.setDoctorName(onlineSession.getDoctorName());
        sendPatientsMedicalRecordDTO.setPatientId(onlineSession.getPatientId());
        sendPatientsMedicalRecordDTO.setPatientName(onlineSession.getPatientName());
        sendPatientsMedicalRecordDTO.setDescript(medicalRecords.getIllnessDescription());
        sendPatientsMedicalRecordDTO.setAskType(sendSysMessageAndPatientsMedicalRecordAO.getAskType());
        sendPatientsMedicalRecordDTO.setPatientOnlineOrderId(sendSysMessageAndPatientsMedicalRecordAO.getPatientOnlineOrderId());
        sendPatientsMedicalRecordDTO.setPatientCardNo(patient.getPatientCardNo());
        sendPatientsMedicalRecordDTO.setHeadUrl(PhotoTools.getFullPath(customConf.getFileUrl(), doctor.getHeadPhoto()));
        return sendPatientsMedicalRecordDTO;
    }

    public static List<DoctorArticleNotificationPatient> buildShareDoctorArticleNotificationPatientList(List<DoctorArticleNotificationPatient> doctorArticleNotificationPatientList, Long doctorArticleId, List<Long> patientIdList) {
        Map<Long, DoctorArticleNotificationPatient> articleNotificationPatientMap = doctorArticleNotificationPatientList.stream().collect(Collectors.toMap(DoctorArticleNotificationPatient::getPatientId, Function.identity(), (key1, key2) -> key2));
        List<DoctorArticleNotificationPatient> list = Lists.newArrayList();
        for (Long patientId : patientIdList) {
            DoctorArticleNotificationPatient doctorArticleNotificationPatient = articleNotificationPatientMap.get(patientId);
            if (doctorArticleNotificationPatient != null) {
                doctorArticleNotificationPatient.setUpdateTime(DateUtil.currDate());
                list.add(doctorArticleNotificationPatient);
                continue;
            }
            doctorArticleNotificationPatient = new DoctorArticleNotificationPatient();
            doctorArticleNotificationPatient.setId(SystemUtil.getId());
            doctorArticleNotificationPatient.setDoctorArticleId(doctorArticleId);
            doctorArticleNotificationPatient.setPatientId(patientId);
            doctorArticleNotificationPatient.setBizStatus(1);
            doctorArticleNotificationPatient.setStatus(0);
            doctorArticleNotificationPatient.setCreatedTime(DateUtil.currDate());
            list.add(doctorArticleNotificationPatient);
        }
        return list;
    }

    public static MessageNotificationDTO buildDoctorArticleNotificationPatientMessageNotification(DoctorArticle doctorArticle, Long userId) {
        MessageNotificationDTO messageNotificationDTO = new MessageNotificationDTO();
        messageNotificationDTO.setTitle("您有一个文章消息");
        messageNotificationDTO.setDescription(null);
        List<MessageNotificationContentDTO> contents = Lists.newArrayList();
        MessageNotificationContentDTO messageNotificationContentDTO = new MessageNotificationContentDTO();
        messageNotificationContentDTO.setLabel("标题");
        messageNotificationContentDTO.setValue(doctorArticle.getTitle());
        contents.add(messageNotificationContentDTO);
        messageNotificationDTO.setContents(contents);
        messageNotificationDTO.setMessageType(5);
        messageNotificationDTO.setUserType(1);
        messageNotificationDTO.setUserId(userId);
        messageNotificationDTO.setDataId(doctorArticle.getId());
        return messageNotificationDTO;
    }

    public static MessageNotificationDTO buildDoctorScheduleNotificationPatientMessageNotification(OrderReg orderReg, Long userId) {
        MessageNotificationDTO messageNotificationDTO = new MessageNotificationDTO();
        messageNotificationDTO.setTitle("您有一个诊前加号");
        messageNotificationDTO.setDescription(null);
        List<MessageNotificationContentDTO> contents = Lists.newArrayList();
        MessageNotificationContentDTO messageNotificationContentDTODoctor = new MessageNotificationContentDTO();
        messageNotificationContentDTODoctor.setLabel("挂号医生");
        messageNotificationContentDTODoctor.setValue(orderReg.getDoctorName());
        contents.add(messageNotificationContentDTODoctor);
        // 处理就诊时间
        MessageNotificationContentDTO messageNotificationContentDTOTime = new MessageNotificationContentDTO();
        messageNotificationContentDTOTime.setLabel("就诊时间");
        Date date = DateUtil.parse(orderReg.getExpectStime(), "yyyy-MM-dd HH:mm:ss");
        String expectTime = new SimpleDateFormat("yyyy-MM-dd ahh:mm").format(date);
        messageNotificationContentDTOTime.setValue(expectTime);
        contents.add(messageNotificationContentDTOTime);
        messageNotificationDTO.setContents(contents);
        messageNotificationDTO.setMessageType(9);
        messageNotificationDTO.setUserType(1);
        messageNotificationDTO.setUserId(userId);
        messageNotificationDTO.setDataId(orderReg.getId());
        return messageNotificationDTO;
    }

    public static SavePatientDTO buildSavePatientDTO(CustomConf customConf, PatientUser patientUser) {
        SavePatientDTO dto = new SavePatientDTO();
        dto.setGender(patientUser.getSex());
        dto.setHeadUrl(customConf.getFileUrl() + patientUser.getHeadPhoto());
        dto.setNickName(patientUser.getNickName());
        dto.setPatientId(patientUser.getId());
        dto.setPhone(patientUser.getPhone());
        dto.setPlatform(10);
        return dto;
    }

    public static SavePatientInquirerDTO buildSavePatientInquirerDTO(Patient patient) {
        SavePatientInquirerDTO dto = new SavePatientInquirerDTO();
        dto.setInquirerId(patient.getId());
        dto.setPatientId(patient.getPatientUserId());
        dto.setPlatform(10);
        dto.setAddress(patient.getContactsAddr());
        dto.setContactName(patient.getContactsName());
        dto.setContactPhone(patient.getContactsPhoneNo());
        dto.setIdCard(patient.getIdCardNo());
        dto.setIsDefault(0);
        dto.setName(patient.getName());
        dto.setPhone(patient.getPhone());
        dto.setRelation(patient.getRelationType());
        return dto;
    }

    public static MessageNotificationDTO buildSendSysMessageAndPatientsMedicalRecord2MessageNotificationDTO(Long patientOnlineOrderId, SendPatientsMedicalRecordDTO sendPatientsMedicalRecordDTO) {
        MessageNotificationDTO messageNotificationDTO = new MessageNotificationDTO();
        messageNotificationDTO.setTitle("发送系统消息和病情描述");
        messageNotificationDTO.setDescription("发送系统消息和病情描述！点击查看");
        messageNotificationDTO.setContents(buildMessageNotificationContentList(sendPatientsMedicalRecordDTO));
        messageNotificationDTO.setMessageType(8);
        messageNotificationDTO.setUserType(1);
        messageNotificationDTO.setUserId(sendPatientsMedicalRecordDTO.getPatientId());
        messageNotificationDTO.setDataId(patientOnlineOrderId);
        return messageNotificationDTO;
    }

    public static MessageNotificationDTO buildSendArticleIM2MessageNotificationDTO(Long userId, DoctorArticle doctorArticle) {
        MessageNotificationDTO messageNotificationDTO = new MessageNotificationDTO();
        messageNotificationDTO.setTitle("文章");
        messageNotificationDTO.setDescription("文章！点击查看");
        List<MessageNotificationContentDTO> contents = new ArrayList<>();
        contents.add(new MessageNotificationContentDTO("标题", doctorArticle.getTitle()));
        messageNotificationDTO.setContents(contents);
        messageNotificationDTO.setMessageType(5);
        messageNotificationDTO.setUserType(1);
        messageNotificationDTO.setUserId(userId);
        messageNotificationDTO.setDataId(doctorArticle.getId());
        return messageNotificationDTO;
    }

    public static MessageNotificationDTO buildSendScheduleIM2MessageNotificationDTO(Long userId, OrderReg orderReg) {
        MessageNotificationDTO messageNotificationDTO = new MessageNotificationDTO();
        messageNotificationDTO.setTitle("您有一个诊前加号");
        messageNotificationDTO.setDescription(null);
        List<MessageNotificationContentDTO> contents = Lists.newArrayList();
        MessageNotificationContentDTO messageNotificationContentDTODoctor = new MessageNotificationContentDTO();
        messageNotificationContentDTODoctor.setLabel("挂号医生");
        messageNotificationContentDTODoctor.setValue(orderReg.getDoctorName());
        contents.add(messageNotificationContentDTODoctor);
        // 处理就诊时间
        MessageNotificationContentDTO messageNotificationContentDTOTime = new MessageNotificationContentDTO();
        messageNotificationContentDTOTime.setLabel("就诊时间");
        Date date = DateUtil.parse(orderReg.getExpectStime(), "yyyy-MM-dd HH:mm:ss");
        String expectTime = new SimpleDateFormat("yyyy-MM-dd ahh:mm").format(date);
        messageNotificationContentDTOTime.setValue(expectTime);
        contents.add(messageNotificationContentDTOTime);
        messageNotificationDTO.setContents(contents);
        messageNotificationDTO.setMessageType(7);
        messageNotificationDTO.setUserType(1);
        messageNotificationDTO.setUserId(userId);
        messageNotificationDTO.setDataId(orderReg.getId());
        return messageNotificationDTO;
    }


    public static <T> List<MessageNotificationContentDTO> buildMessageNotificationContentList(T t) {
        Map<String, Object> result = JSON.parseObject(JSON.toJSONString(t), Map.class);
        List<MessageNotificationContentDTO> list = new ArrayList<>();
        MessageNotificationContentDTO messageNotificationContentDTO = null;
        for (Map.Entry<String, Object> entry : result.entrySet()) {
            messageNotificationContentDTO = new MessageNotificationContentDTO();
            messageNotificationContentDTO.setLabel(entry.getKey());
            Object value = entry.getValue();
            messageNotificationContentDTO.setValue(value == null ? null : value.toString());
            list.add(messageNotificationContentDTO);
        }
        return list;
    }
}
